<template>
  <div style="max-width: 800px; margin: 16px auto; padding: 0 12px;">
    <a-card title="权限测试页面">
      <a-descriptions bordered :column="1">
        <a-descriptions-item label="当前用户信息">
          <pre>{{ JSON.stringify(userProfile, null, 2) }}</pre>
        </a-descriptions-item>
        <a-descriptions-item label="权限列表">
          <a-tag v-for="perm in permissions" :key="perm" color="blue">{{ perm }}</a-tag>
          <span v-if="!permissions.length" class="text-muted">无权限</span>
        </a-descriptions-item>
        <a-descriptions-item label="文件管理权限">
          <a-tag :color="hasOssManage ? 'green' : 'red'">
            {{ hasOssManage ? '有权限' : '无权限' }}
          </a-tag>
        </a-descriptions-item>
      </a-descriptions>
      
      <div style="margin-top: 16px;">
        <h3>权限检查结果：</h3>
        <ul>
          <li>oss:manage - <span :style="{ color: hasOssManage ? 'green' : 'red' }">{{ hasOssManage ? '✓' : '✗' }}</span></li>
          <li>article:write - <span :style="{ color: hasPerm('article:write') ? 'green' : 'red' }">{{ hasPerm('article:write') ? '✓' : '✗' }}</span></li>
          <li>user:manage - <span :style="{ color: hasPerm('user:manage') ? 'green' : 'red' }">{{ hasPerm('user:manage') ? '✓' : '✗' }}</span></li>
          <li>permission:manage - <span :style="{ color: hasPerm('permission:manage') ? 'green' : 'red' }">{{ hasPerm('permission:manage') ? '✓' : '✗' }}</span></li>
        </ul>
      </div>
      
      <div style="margin-top: 16px;">
        <a-button type="primary" @click="testOssAccess">测试访问文件管理页面</a-button>
        <a-button style="margin-left: 8px;" @click="refreshPermissions">刷新权限</a-button>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { usePerm } from '@/composables/usePerm'

const router = useRouter()
const { hasPerm } = usePerm()

const userProfile = ref<any>(null)

const permissions = computed(() => {
  if (!userProfile.value?.perms) return []
  return userProfile.value.perms.split(',').map((p: string) => p.trim()).filter(Boolean)
})

const hasOssManage = computed(() => hasPerm('oss:manage'))

function loadUserProfile() {
  try {
    const profile = localStorage.getItem('profile')
    userProfile.value = profile ? JSON.parse(profile) : null
  } catch (error) {
    console.error('解析用户信息失败:', error)
    userProfile.value = null
  }
}

function refreshPermissions() {
  loadUserProfile()
  message.success('权限信息已刷新')
}

function testOssAccess() {
  if (hasOssManage.value) {
    router.push('/admin/oss')
    message.success('跳转到文件管理页面')
  } else {
    message.error('没有文件管理权限，无法访问')
  }
}

onMounted(() => {
  loadUserProfile()
})
</script>

<style scoped>
.text-muted {
  color: #999;
}
</style>
